<?php

namespace AdminModule;

use \AdminModule\Helpers\Image;

class VzorkovnaPresenter extends AdminPresenter {

    private $dataFilter = array('id_manufacturer', 'code', 'id_tile_type', 'width', 'height', 'price', 'action', 'id_image');

    public function actionDefault() {
        $showroomModel = new Models\Showroom($this->db);
        $this->template->showrooms = $showroomModel;
    }

    public function actionPridat() {
        $showroomSection = $this->getContext()->getService('session')->getSection('showroom');
        $tiles = array();
        if (!empty($showroomSection->addedTiles) && is_array($showroomSection->addedTiles)) {
            $tilesIds = $showroomSection->addedTiles;
            $tileModel = new Models\Tile($this->db);
            $tiles = $tileModel->where('id_tile IN (' . implode(', ', $tilesIds) . ')');
        }
        $this->template->tiles = $tiles;
    }

    public function actionUpravit($id) {
        $showroomModel = new Models\Showroom($this->db);
        $showroom = $showroomModel->get($id);
        if (!$showroom instanceof \Nette\Database\Table\ActiveRow) {
            $this->flashMessage('Kóje s požadovaným id neexistuje', 'error');
            $this->redirect('default');
        }
    }

    public function actionObrazky($id) {
        $this->setShowroomToTemplate($id);
        $imageModel = new Models\Image($this->db);
        $images = $imageModel->getShowroomImages($this->template->showroom);
        $this->template->images = $images;
    }

    public function actionPolozky($id) {
        $this->setShowroomToTemplate($id);
        $tileAddModel = new Models\Tile($this->db);
        $tilesForAdd = $tileAddModel->getForShowroom($this->template->showroom);
        $this->template->tilesForAdd = $tilesForAdd;
    }

    public function handlePridatPolozku($idShowroom, $idTile) {
        $showroomHasFilesModel = new \AdminModule\Models\ShowroomHasTiles($this->db);
        $data = array(
            'id_showroom' => $idShowroom,
            'id_tile' => $idTile,
        );
        if ($showroomHasFilesModel->insert($data) !== FALSE) {
            $this->flashMessage('Položka byla přidána');
        } else {
            $this->flashMessage('Položku se nepodařilo přidat');
        }
        $this->invalidateControl('content');
        if (!$this->isAjax()) {
            $this->redirect('this');
        }
    }

    public function handleOdebratPolozku($idShowroom, $idTile) {
        $sql = 'DELETE FROM showroom_has_tiles WHERE id_showroom = ? AND id_tile = ?';
        $numberOfAffectedRows = $this->db->exec($sql, $idShowroom, $idTile);

        if ($numberOfAffectedRows > 0) {
            $this->flashMessage('Položka byla odebrána');
        } else {
            $this->flashMessage('Položku se nepodařilo odebrat', 'error');
        }
        if (!$this->isAjax()) {
            $this->redirect('this');        
        }
    }

    public function handleSmazatObrazek($idShowroom, $idImage) {
        $showroomImageModel = new Models\ShowroomHasiImage($this->db);
        $data = array($idShowroom, $idImage);
        $numberOfAffectedRows = $showroomImageModel->where('id_showroom = ? AND id_image = ?', $data)->delete();
        if ($numberOfAffectedRows > 0) {
            $imageForDeleteModel = new Models\Image($this->db);
            $imageForDelete = $imageForDeleteModel->get($idImage);
            $imageModel = new Models\Image($this->db);
            $imageModel->deleteImageFile($imageForDelete);
            $imageForDelete->delete();
            $this->flashMessage('Obrázek byl smazán');
        } else {
            $this->flashMessage('Smazání obrázku se nepodařilo', 'error');
        }
        
        $this->redirect('this');        
    }

    // TODO: je potreba odstranit vsechny zaznamy a obrazky z showroom_has_images
    public function handleSmazat($id) {
        $showroomModel = new Models\Showroom($this->db);
        $showroom = $showroomModel->get($id);

        try {
            $this->deleteAllShowroomImages($showroom);
            if ($showroom->delete($showroom)) {
                $this->flashMessage('Kóje byla smazána.');
            } else {
                $this->flashMessage('Kóji se nepodařilo smazat.', 'error');
            }
        } catch (\Exception $exception) {
            $this->flashMessage('Kóji se nepodařilo smazat', 'error');
        }
        $this->invalidateControl('content');

        if (!$this->isAjax()) {
            $this->redirect('this');
        }
    }

    /**
     * Smazani vsech obrazku koje.
     * 
     * @param type \Nette\Database\Table\ActiveRow
     */
    private function deleteAllShowroomImages(\Nette\Database\Table\ActiveRow $showroom) {
        $imageModel = new \AdminModule\Models\Image($this->db);
        foreach ($showroom->related('showroom_has_images') as $showroomHasImage) {
            $image = $showroomHasImage->image;
            $imageModel->deleteWithFileByImageId($image->id_image);
        }
    }

    public function handleStahnout($id) {
        $showroomModel = new Models\Showroom($this->db);
        $showroom = $showroomModel->get($id);
        if (!$showroom instanceof \Nette\Database\Table\ActiveRow) {
            $this->flashMessage('Kóje s požadovaným id neexistuje', 'error');
            $this->redirect('default');
        }
        if ($showroom->update(array('published' => false))) {
            $this->flashMessage('Kóje byla stažena z webu');
        } else {
            $this->flashMessage('Kóji se nepodařilo z webu stáhnout', 'error');
        }

        $this->invalidateControl('content');

        if (!$this->isAjax()) {
            $this->redirect('this');
        }
    }

    public function handleZverejnit($id) {
        $showroomModel = new Models\Showroom($this->db);
        $showroom = $showroomModel->get($id);
        if (!$showroom instanceof \Nette\Database\Table\ActiveRow) {
            $this->flashMessage('Kóje s požadovaným id neexistuje', 'error');
            $this->redirect('default');
        }

        if (count($showroom->related('showroom_has_images')) < 1) {
            $this->flashMessage('Kóji nelze uveřejnit, protože nemá přiřazen žádný obrázek', 'error');
        } else if ($showroom->update(array('published' => true))) {
            $this->flashMessage('Kóje byla zveřejněna');
        } else {
            $this->flashMessage('Kóji se nepodařilo zveřejnit', 'error');
        }

        $this->invalidateControl('content');

        if (!$this->isAjax()) {
            $this->redirect('this');
        }
    }

    private function setShowroomToTemplate($id) {
        $showroomModel = new Models\Showroom($this->db);
        $showroom = $showroomModel->get($id);
        if (!$showroom instanceof \Nette\Database\Table\ActiveRow) {
            $this->flashMessage('Kóje s požadovaným id neexistuje', 'error');
            $this->redirect('default');
        }
        $this->template->showroom = $showroom;
    }

    protected function createComponentShowroomForm($name) {
        $form = new \Nette\Application\UI\Form;
        $manufacturer = new Models\Manufacturer($this->db);
        $manufacturersOptions = $manufacturer->getSelectOptions();

        $form->addText('title', 'Série');
        $form->addTextArea('description', 'Popis');
        $manufacturerSelect = $form->addSelect('id_manufacturer', 'Výrobce', $manufacturersOptions);
        $form->addSubmit('save', 'Uložit');
        $form->onSuccess[] = callback($this, 'showroomFormSubmitted');

        if ($this->action == 'upravit') {
            $showroomModel = new Models\Showroom($this->db);
            $showroom = $showroomModel->get($this->getParameter('id'));
            $form->setDefaults($showroom);
            $manufacturerSelect->setDisabled();
        }

        $this[$name] = $form;
        $form->action .= '#snippet--usersForm';
        return $form;
    }

    public function showroomFormSubmitted(\Nette\Application\UI\Form $form) {
        $values = $form->getValues();

        $showroomModel = new Models\Showroom($this->db);

        if ($this->action == 'pridat') {
            $showroomModel->insert($values);
            $this->flashMessage('Kóje byla přidána');
            $this->redirect('default');
        } else if ($this->action == 'upravit') {
            $showroomModel = new Models\Showroom($this->db);
            $showroom = $showroomModel->get($this->getParameter('id'));
            $showroom->update($values);
            $this->flashMessage('Kóje byla upravena');
            $this->redirect('this');
        }

        $this->redirect('default');
    }

    protected function createComponentImageForm() {
        $form = new \Nette\Application\UI\Form;
        $form->addText('title', 'Název');
        $form->addText('description', 'Popis');
        $form->addUpload('image', 'Soubor s obrázkem')
                ->setRequired('Vložte soubor s obrázkem');
        $form->addHidden('type')->setValue(\AdminModule\Helpers\Image::TYPE_SHOWROOM);
        $form->addSubmit('add', 'Přidat');
        $form->onSuccess[] = $this->imageFormSubmitted;
        return $form;
    }

    public function imageFormSubmitted(\Nette\Application\UI\Form $form) {
        $values = $form->getValues(true);
        $imageModel = new Models\Image($this->db);
        try {
            $image = $imageModel->insert($values);
            $showroomImageModel = new Models\ShowroomHasiImage($this->db);
            $showroomImageModel->insert(array(
                'id_showroom' => $this->getParameter('id'),
                'id_image' => $image->id_image,
            ));
            $this->flashMessage('Obrázek byl přidán');
        } catch (\LogicException $exception) {
            $this->flashMessage('Přidání obrázku se nezdařilo: ' . $exception->getMessage());
        }
        $this->redirect('this');
    }

}
